package com.customization.unionpay.market.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.wbi.util.StringUtil;
import com.weaver.general.Util;
import weaver.backup.logging.Logger;
import weaver.backup.logging.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;

import java.util.ArrayList;
import java.util.List;

public class FormDataUtil {

    private static final Logger log = LoggerFactory.getLogger(FormDataUtil.class);


    /**
     * 获取表单中下拉框的枚举值
     *
     * @param formId
     * @param fieldName
     * @param selectName
     * @return
     */
    public static List<JSONObject> getSelectItem(int formId, String fieldName, String selectName) {

        RecordSet rs = new RecordSet();
        List<JSONObject> results = new ArrayList<>();

        if (ObjectUtil.isEmpty(formId)) {
            log.error("表单id为空");
            return results;
        }

        StringBuilder builder = new StringBuilder();
        builder.append("select ws.selectname as name ,ws.selectvalue as value ,ws.fieldid as fieldId " +
                "from workflow_billfield b " +
                "JOIN workflow_SelectItem ws " +
                "ON ws.fieldid = b.id " +
                "where b.fieldhtmltype = 5 and b.billid = ").append(formId);
        if (StringUtil.isNotBlank(fieldName)){
            builder.append(" and b.fieldname = '").append(fieldName).append("'");
        }
        if(StringUtil.isNotBlank(selectName)){
            builder.append(" and ws.selectname = '").append(selectName).append("'");
        }
        try {
            rs.execute(builder.toString());
            while (rs.next()){
                JSONObject result = new JSONObject();
                result.put("name", Util.null2String(rs.getString("name")));
                result.put("value",Util.null2String(rs.getString("value")));
                results.add(result);
            }
        }catch (Exception e){
            log.error("查询枚举值错误"+e.getMessage());
        }
        return results;

    }

    public static void permissionReset(int modalId,String formName){
        ModeRightInfo model = new ModeRightInfo();
        model.setNewRight(true);

        StringBuilder sql = new StringBuilder();
        sql.append("select id,formmodeid,modedatacreater from ")
                .append(formName).append(" t1 ")
                .append(" where not exists ( select * from modedatashare_")
                .append(modalId).append(" t2 where t1.id = t2.sourceid )");
        RecordSet rs = new RecordSet();
        try {
            rs.execute(sql.toString());
            while (rs.next()){
                int id = rs.getInt("id");
                int formmodeid = rs.getInt("formmodeid");
                int createrid = rs.getInt("modedatacreater");
                model.editModeDataShare(createrid,formmodeid,id);
            }
        }catch (Exception e){
            log.error("权限重置失败");
        }

     }


}
